<template>
	<view>
		<fui-input :label="label" :placeholder="placeholder" label-size="26" placeholderStyle="fontSize:26rpx"
			v-model="text">
			<template #default v-if="isCode">
				<fui-button type="primary" width="160rpx" height="50rpx" size='5' @click="getCode"
					:disabled="countdown > 0">
					{{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
				</fui-button>
			</template>
		</fui-input>
	</view>
</template>

<script>
	export default {
		name: "lableInput",
		props: {
			label: {
				type: String,
				default: "",
			},
			placeholder: {
				type: String,
				default: "",
			},
			isCode: {
				type: Boolean,
				default: false,
			},
			modelValue: {
				type: String,
				default: ""
			},
			phone: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				text: this.modelValue,
				countdown: 0,
				timer: null,
			};
		},
		methods: {
			isValidPhone(phone) {
				const reg = /^1[3-9]\d{9}$/;
				return reg.test(phone);
			},
			getCode() {
				if (this.countdown > 0) return;
				if (!this.phone) {
					uni.showToast({
						title: '账号不能为空',
						icon: 'none'
					});
					return;
				}
				if (!this.isValidPhone(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号格式',
						icon: 'none'
					});
					return;
				}
				// 触发父组件的获取验证码事件
				this.$emit('get-code');
				// 开始倒计时
				this.countdown = 20;
				this.timer = setInterval(() => {
					this.countdown--;
					if (this.countdown <= 0) {
						clearInterval(this.timer);
					}
				}, 1000);
			}
		},
		watch: {
			text(val) {
				this.$emit('update:modelValue', val);
			},
			modelValue(val) {
				this.text = val;
			}
		},
		beforeUnmount() {
			// 组件销毁前清除定时器
			if (this.timer) {
				clearInterval(this.timer);
			}
		}
	};
</script>

<style lang="scss"></style>